package com.xqboss.apps.service.hama;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xqboss.apps.constant.Config;
import com.xqboss.apps.constant.RedisKey;
import com.xqboss.apps.domain.hama.*;
import com.xqboss.apps.dto.PageDto;
import com.xqboss.apps.dto.hama.*;
import com.xqboss.apps.enums.hama.*;
import com.xqboss.apps.enums.mq.AppMqDelayEnum;
import com.xqboss.apps.enums.nft.UserNftStatusEnum;
import com.xqboss.apps.enums.user.WalletChangeDirectionEnum;
import com.xqboss.apps.enums.user.WalletLidouChangeTypeEnum;
import com.xqboss.apps.mapper.hama.HamaUserMixMapper;
import com.xqboss.apps.service.nft.NftService;
import com.xqboss.apps.service.user.SysUserNftService;
import com.xqboss.apps.service.user.UserAssetLidouService;
import com.xqboss.apps.util.mh.MoneyUtils;
import com.xqboss.apps.vo.hama.*;
import com.xqboss.common.core.domain.R;
import com.xqboss.common.core.domain.entity.SysUser;
import com.xqboss.common.core.domain.model.LoginUser;
import com.xqboss.common.core.mq.MqSender;
import com.xqboss.common.core.redis.RedisCache;
import com.xqboss.common.exception.ServiceException;
import com.xqboss.common.utils.DateUtils;
import com.xqboss.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

import static com.xqboss.common.utils.AsyncHandlerUtil.*;


/**
 * <p>
 * 挖灵珠速率 服务实现类
 * </p>
 *
 * @author 木鱼
 * @since 2024-02-28
 */
@Service
@Slf4j
public class HamaUserMixService extends ServiceImpl<HamaUserMixMapper, HamaUserMix> {

    @Autowired
    private HamaMixConfigService hamaMixConfigService;
    @Autowired
    private HamaConfigNumberService hamaConfigNumberService;
    @Autowired
    private HamaHelpService hamaHelpService;
    @Autowired
    private HamaMixLogService hamaMixLogService;
    @Autowired
    private HamaOpenConfigService hamaOpenConfigService;
    @Autowired
    private HamaUserOpenService hamaUserOpenService;
    @Autowired
    private UserAssetLidouService userAssetLidouService;
    @Autowired
    private ISysConfigService sysConfigService;
    @Autowired
    private NftService nftService;
    @Autowired
    private SysUserNftService sysUserNftService;
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private MqSender mqSender;




    //*****************************************************************************************************************
    //***********************************************app相关************************************************************
    //*****************************************************************************************************************

    /**
     * 运动场首页个人相关信息
     *
     * @param userId 用户id
     * @return 信息
     */
    public HamaUserMixVO getHamaMix(Long userId) {
        // 获取用户当前的装备信息
        HamaUserMix mix = this.lambdaQuery().eq(HamaUserMix::getUserId, userId).one();
        boolean isNotEmpty = ObjUtil.isNotEmpty(mix);
        // 查询力豆余额
        BigDecimal lidou = MoneyUtils.toBigDecimal2(this.userAssetLidouService.getLidouInfo(userId).getAmount());
        // 返回
        return HamaUserMixVO.builder()
                .basicSpeed(isNotEmpty?MoneyUtils.toBigDecimal2(mix.getBasicSpeed()):BigDecimal.ZERO)//每小时产多少力豆
                .hamaNumber(isNotEmpty?getWaNumber(userId):0)
                .lidou(lidou)
                .build();
    }


    /**
     * 运动场装备列表信息
     *
     * @param userId 用户id
     * @return 信息
     */
    public IPage<HamaUserMixInfoVO> getHamaMixList(Long userId, PageDto<HamaMixConfig> dto) {
        // 获取所有可投放装备的数据
        Page<HamaMixConfig> page = this.hamaMixConfigService.page(dto.newPage(), new LambdaQueryWrapper<HamaMixConfig>().eq(HamaMixConfig::getState, 1).orderByDesc(HamaMixConfig::getCreateTime));
        IPage<HamaUserMixInfoVO> iPage = new Page<>();
        if (ObjUtil.isNotEmpty(page) && CollUtil.isNotEmpty(page.getRecords())) {
            iPage.setTotal(page.getTotal());
            List<HamaMixConfig> configs = page.getRecords();
            List<HamaUserMixInfoVO> infos = new ArrayList<>(configs.size());
            Integer maxNumber = this.sysConfigService.getValue(Config.Sys.Sport.一次性允许最大装备的数量);
            Map<Long, Integer> nftNumber = getNftNumber(userId);
            for (HamaMixConfig config : configs) {
                // 藏品图片路径
                String nftImg = this.nftService.getNftMainImg(config.getNftId());
                // 藏品剩余数量
                int leaveNumber = this.sysUserNftService.getNftNumberCounts(config.getNftId(), userId).intValue();
                // 藏品可投放最大数量(要求去除自己已投的数量)
                int max = 0;
                // 获取该藏品空投周期中已投数量
                if (CollUtil.isNotEmpty(nftNumber) && nftNumber.get(config.getNftId())!=null) {
                    max = config.getToplimit() - nftNumber.get(config.getNftId());
                }
                max = max==0?config.getToplimit():max;  // 若max为0，说明该用户还没有投放过装备，那么最大的投放量 ，取该装备配置的
                int max1 = Math.min(leaveNumber,maxNumber);
                max = Math.min(max,max1);
                max = Math.max(max, 0);
                // 藏品可召唤蛙星人数量
                int hamaNumber = max * config.getSportMix();
                // 预计空投力豆
                BigDecimal basicSpeed = this.hamaConfigNumberService.getBasicSpeed(HamaConfigNumberTypeEnum.ONE, HamaConfigNumberPeopleEnum.OLD,hamaNumber);
                BigDecimal lidou = MoneyUtils.multipleToScale2(basicSpeed,24*config.getHireDays());
                infos.add(
                        HamaUserMixInfoVO.builder()
                                .nftId(config.getNftId())
                                .nftImg(nftImg)
                                .leaveNumber(leaveNumber)
                                .max(max)
                                .hamaNumber(hamaNumber)
                                .lidou(lidou)
                                .build()
                );
            }
            iPage.setRecords(infos);
        }
        return iPage;
    }
    /**
     * 运动场首页动态数据
     *
     * @param number 投装备数量
     * @param userId 用户id
     * @param nftId 装备id
     * @return 信息
     */
    public HamaUserMixInfoTrendsVO getMixTrends(int number, Long userId, Long nftId) {
        Assert.notNull(userId,()->new ServiceException("用户不存在~"));
        HamaMixConfig mixConfig = this.hamaMixConfigService.getCacheData(nftId);
        // 可召唤蛙星人数量
        int hamaNumber = number*mixConfig.getSportMix();
        // 预计空投力豆
        BigDecimal basicSpeed = this.hamaConfigNumberService.getBasicSpeed(HamaConfigNumberTypeEnum.ONE, HamaConfigNumberPeopleEnum.OLD,hamaNumber);
        BigDecimal lidou = MoneyUtils.multipleToScale2(basicSpeed,24*mixConfig.getHireDays());
        return HamaUserMixInfoTrendsVO.builder().hamaNumber(hamaNumber).lidou(lidou).build();
    }

    /**
     * 获取用户装备加油手环的记录列表
     *
     * @param page 分页
     * @param userId 用户id
     * @return 列表
     */
    public IPage<HamaMixLog> getHamaMixLog(Page<HamaMixLog> page,Long userId) {

        return this.hamaMixLogService.getHamaMixLog(page,userId);
    }

    /**
     * 装备加油手环
     *
     * @param number 装备的手环数量
     * @param userId 用户id
     * @param nftId 所投放装备的id
     * @return 投放信息
     */
    @Transactional
    public R<HamaUserMix> employNft(int number, Long userId, Long nftId){
        Date indexTime = new Date();
        LocalDateTime localDateTime = indexTime.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime();
        // 藏品配置
        HamaMixConfig hamaMixConfig = this.hamaMixConfigService.getCacheData(nftId);
        if (ObjUtil.isEmpty(hamaMixConfig)) {
            R.fail("非法参数~");
        }
        if (hamaMixConfig.getToplimit()==0) {
            R.fail("暂未开放~");
        }
        String msg = HamaNftTypeEnum.getNftName(hamaMixConfig.getNftId());
        // 查询剩余手环数量
        Long[] nftLeaveInfo = this.hamaMixConfigService.getNftLeaveInfo(hamaMixConfig.getNftId(),userId, number);
        int nftNumber=nftLeaveInfo==null?0:nftLeaveInfo.length;
        if(nftNumber<number){
            return R.fail(nftNumber==0?"还没有"+msg+"~":msg+"数量不足，只有"+nftNumber+"张~");
        }
        // 是否超过限制
        HamaUserMix hamaUserMix = this.lambdaQuery().eq(HamaUserMix::getUserId,userId).one();
        // 获取 运动场投放装备蛙星人倍率
        boolean notEmpty = ObjectUtils.isNotEmpty(hamaUserMix);
        List<HamaMixLog> list = this.hamaMixLogService.lambdaQuery().eq(HamaMixLog::getNftId, nftId).eq(HamaMixLog::getUserId,userId).eq(HamaMixLog::getIsHire, HamaMixLogHireEnum.YES).list();
        int beforeNum =  CollUtil.isNotEmpty(list)?list.stream().mapToInt(HamaMixLog::getHamaNumber).sum():0;
        int hasNum = beforeNum + number;// 已投装备数量，在空投周期中的
        if(hasNum>hamaMixConfig.getToplimit()){
            return R.fail(msg+"投放超过上限~");
        }

        //添加投放装备记录
        Date hireTime= DateUtils.add(localDateTime,hamaMixConfig.getHireDays());
        HamaMixLog hamaMixLog=new HamaMixLog();
        hamaMixLog.setUserId(userId);
        hamaMixLog.setNftId(nftId);
        hamaMixLog.setHamaNumber(number);
        hamaMixLog.setHireTime(hireTime);
        hamaMixLog.setCreateTime(localDateTime);
        hamaMixLog.setIsHire(HamaMixLogHireEnum.YES);
        Assert.isTrue(hamaMixLogService.save(hamaMixLog),()->new ServiceException("投放"+msg+"失败~"));

        Integer waNumber = getWaNumber(userId);//蛙星人数量
        if(notEmpty){
            //修改用户浑天灵池
            BigDecimal basicSpeed = this.hamaConfigNumberService.getBasicSpeed(HamaConfigNumberTypeEnum.ONE, HamaConfigNumberPeopleEnum.OLD, waNumber);
            hamaUserMix.setBasicSpeed(basicSpeed);
            hamaUserMix.setNumber(hamaUserMix.getNumber()+number);
            hamaUserMix.setUpdateTime(localDateTime);
            Assert.isTrue(this.updateById(hamaUserMix),()->new ServiceException("投放"+msg+"失败~"));
        }else {
            // 添加用户浑天灵池
            BigDecimal basicSpeed = this.hamaConfigNumberService.getBasicSpeed(HamaConfigNumberTypeEnum.ONE, HamaConfigNumberPeopleEnum.OLD, waNumber);
            hamaUserMix=new HamaUserMix();
            hamaUserMix.setUserId(userId);
            hamaUserMix.setBasicSpeed(basicSpeed);
            hamaUserMix.setEggLayingNum(BigDecimal.ZERO);
            hamaUserMix.setNumber(number);
            hamaUserMix.setStartProductionTime(indexTime);
            hamaUserMix.setCreateTime(localDateTime);
            Assert.isTrue(this.save(hamaUserMix),()->new ServiceException("投放"+msg+"失败~"));
        }

        // 查询当前用户是否助力
        HamaHelp hamaHelp= this.hamaHelpService.lambdaQuery().eq(HamaHelp::getChildUserId,userId).one();
        if(ObjectUtils.isNotEmpty(hamaHelp)){
            if (hamaHelp.getBasicSpeed().compareTo(BigDecimal.ZERO)==0) {
                hamaHelp.setStartProductionTime(indexTime);
            }
            BigDecimal basicSpeed = this.hamaConfigNumberService.getBasicSpeed(HamaConfigNumberTypeEnum.TWO, HamaConfigNumberPeopleEnum.OLD, waNumber);
            hamaHelp.setNumber(hamaUserMix.getNumber());
            hamaHelp.setBasicSpeed(basicSpeed);
            hamaHelp.setIsPeople(HamaConfigNumberPeopleEnum.OLD);
            hamaHelp.setIsRealName(Boolean.TRUE);
            // 修改用户最新速度 助力速度
            Assert.isTrue(this.hamaHelpService.updateById(hamaHelp),()->new ServiceException("投放"+msg+"失败~"));
        }

        //去除对应手环
        this.hamaMixConfigService.burnNftLeaveInfo(nftLeaveInfo,userId, UserNftStatusEnum.SPORT_MIX_BURN);
        hamaUserMix.setBasicSpeed(MoneyUtils.toBigDecimal2(hamaUserMix.getBasicSpeed()));
        return R.ok(hamaUserMix,"投放"+msg+"成功~");
    }


    /**
     * 我的队伍首页信息
     *
     * @param userId 用户id
     * @return 信息
     */
    public HamaHelpVO teamHelp(Long userId) {
        //查询自己给上级助力多少
        HamaHelp hamaHelp= this.hamaHelpService.lambdaQuery().eq(HamaHelp::getChildUserId,userId).one();
        boolean notEmpty = ObjectUtils.isNotEmpty(hamaHelp);
        // 是否创建过队伍
        HamaHelpJoinTypeEnum isCreate = this.hamaHelpService.isCreateTeam(userId,HamaConfigNumberPeopleEnum.ADMIN);
        HamaHelpVO vo = new HamaHelpVO();
        vo.setParentUserNick(notEmpty?hamaHelp.getParentUserNick():null);
        vo.setEggLayingNum(notEmpty?( hamaHelp.getIsPeople()==HamaConfigNumberPeopleEnum.NEW?MoneyUtils.toBigDecimal6(hamaHelp.getEggLayingNum()).stripTrailingZeros():MoneyUtils.toBigDecimal2(hamaHelp.getEggLayingNum()) ):BigDecimal.ZERO);
        vo.setIsUnit(notEmpty?HamaHelpUnitEnum.YES:HamaHelpUnitEnum.NO);
        vo.setType(isCreate);
        // 创建了队伍（直推和间推数据）
        if (isCreate == HamaHelpJoinTypeEnum.YES) {
            BigDecimal factor = this.sysConfigService.getValue(Config.Sys.Sport.间推助力系数);
            List<Runnable> runnables = new ArrayList<>(6);
            runnables.add(()->vo.setBasicSpeed(this.hamaHelpService.getBaseMapper().sumManSpeed(userId) ,this.hamaHelpService.getBaseMapper().sumManSpeedSon(userId), factor ));
            runnables.add(()->vo.setManNumber(this.hamaHelpService.getBaseMapper().countManNumber(userId)));
            runnables.add(()->vo.setDirectAirdropTotal(this.hamaHelpService.getBaseMapper().sumManHelpDirect(userId)));
            runnables.add(()->vo.setDirectNumber(this.hamaHelpService.getBaseMapper().sumManDirect(userId)));
            runnables.add(()->vo.setIndirectAirdropTotal(this.hamaHelpService.getBaseMapper().sumManHelpIndirect(userId)));
            runnables.add(()->vo.setIndirectNumber(this.hamaHelpService.getBaseMapper().sumManInDirect(userId)));
            runAllJoin(runnables);
        }
        // 返回
        return vo;
    }

    /**
     * 我的队伍信息
     *
     * @param dto dto
     * @param userId 用户id
     * @return 信息
     */
    public IPage<HamaHelpMyUserVO> getMyTeam(SportMyTeamDto<HamaHelp> dto, Long userId) {
        IPage<HamaHelp> iPage = this.hamaHelpService.getMyTeam(dto.getPush(),dto.getType(),dto.newPage(),userId);
        List<HamaHelpMyUserVO> vos = new ArrayList<>();
        HamaHelpMyUserVO vo = null;
        if (ObjUtil.isNotEmpty(iPage) && CollUtil.isNotEmpty(iPage.getRecords())) {
            for (HamaHelp record : iPage.getRecords()) {
                vo = new HamaHelpMyUserVO();
                vo.setParentUserNick(record.getParentUserNick());
                vo.setChildUserNick(record.getUserNick());
                vo.setBasicSpeed(MoneyUtils.toBigDecimal6(record.getBasicSpeed()));
                vo.setEggLayingNum(dto.getPush()==1?MoneyUtils.toBigDecimal6(record.getEggLayingNum()):MoneyUtils.toBigDecimal6(record.getEggLayingNumIndirect()));
                vo.setIsRealName(record.getIsRealName());
                vo.setType(getType(record));
                if (dto.getPush()==1) vo.setIndirectNumber(this.hamaHelpService.getBaseMapper().sumManDirect(record.getChildUserId()));
                vos.add(vo);
            }
        }
        // 返回
        IPage<HamaHelpMyUserVO> voiPage = new Page<>();
        voiPage.setRecords(vos);
        voiPage.setTotal(iPage.getTotal());
        return voiPage;
    }

    /**
     * 1 新人 2全力助力 3失效 4-未实名
     *
     * @param record 记录
     * @return 状态
     */

    private static Integer getType(HamaHelp record) {
        if (!record.getIsRealName()) {
            return 4;
        }
        return record.getBasicSpeed().compareTo(BigDecimal.ZERO) < 1 ? HamaConfigNumberPeopleEnum.LOSE.getValue() : record.getIsPeople().getValue();
    }

    /**
     * 创建队伍
     *
     * @param loginUser 用户信息
     * @return 信息
     */
    @Transactional
    public R<String> createTeam(LoginUser loginUser) {
        Long count = this.hamaHelpService.lambdaQuery()
                .eq(HamaHelp::getMobile, loginUser.getUsername())
                .eq(HamaHelp::getParentUserId, loginUser.getUserId())
                .count();
        if(count>0){
            return R.fail("已经创建队伍~");
        }
        HamaHelp hamaHelp=new HamaHelp();
        hamaHelp.setParentUserId(loginUser.getUserId());
        hamaHelp.setParentUserNick(loginUser.getNickName());
        hamaHelp.setMobile(loginUser.getUsername());
        hamaHelp.setIsPeople(HamaConfigNumberPeopleEnum.ADMIN);
        hamaHelp.setBasicSpeed(BigDecimal.ZERO);
        hamaHelp.setIsRealName(Boolean.TRUE);
        if (!this.hamaHelpService.save(hamaHelp)) {
            return R.fail("创建队伍失败~");
        }
        return R.ok_msg("创建队伍成功~");
    }

    /**
     * 加入队伍
     *
     * @param teamUser 用户信息-队长
     * @param joinUser 用户信息-加入队伍
     * @param isRealName 加入队伍用户是否实名
     * @return 信息
     */
    @Transactional
    public R<Object> joinTeam(SysUser teamUser,SysUser joinUser,boolean isRealName) {
        Date indexTime = new Date();
        // 判断上级用户是否已经创建队伍
        List<HamaHelp> hamaHelp= this.hamaHelpService.lambdaQuery()
                .eq(HamaHelp::getMobile,teamUser.getUserName())
                .eq(HamaHelp::getParentUserId,teamUser.getUserId())
                .list();
        if(CollectionUtils.isEmpty(hamaHelp)){
            return R.fail("队伍不存在，请重新加入队伍~");
        }
        if(hamaHelp.size()>1){
            return R.fail("队长加入的自己队伍，请联系管理员~");
        }
        // 判断当前用户是否已经加入过队伍
        Long count = this.hamaHelpService.lambdaQuery().eq(HamaHelp::getChildUserId, joinUser.getUserId()).count();
        if(count > 0){
            return R.fail("已经加入过队伍~");
        }
        // 查询加入队伍的队长 有没有加入到其它的队伍，有的话，需要判断加入的是不是当前用户要加入队伍创建的队伍 （即：不能加入自己队员创建的队伍~）
        joinTeamJudge(joinUser.getUserId(),teamUser.getUserId());

        // 加入队伍
        HamaHelp help=new HamaHelp();
        help.setParentUserId(hamaHelp.get(0).getParentUserId());
        help.setParentUserNick(hamaHelp.get(0).getParentUserNick());
        help.setMobile(joinUser.getUserName());
        help.setChildUserId(joinUser.getUserId());
        help.setUserNick(joinUser.getNickName());
        help.setIsRealName(isRealName);
        // 查询当前用户是否是新人
        HamaUserMix hamaUserMix= this.lambdaQuery().eq(HamaUserMix::getUserId,joinUser.getUserId()).one();
        Integer day = this.sysConfigService.getValue(Config.Sys.Sport.几天内注册的用户加入运动场算新人);
        boolean isNew = DateUtil.betweenDay(joinUser.getCreateTime(), indexTime, false) <= day;// 3天内注册的用户为新人
        if(ObjectUtils.isEmpty(hamaUserMix) && isNew){
            // 新人查询对应配置
            HamaConfigNumber hamaConfigNumber = this.hamaConfigNumberService.getBasicSpeedNew();
            help.setBasicSpeed(isRealName?hamaConfigNumber.getBasicSpeed():BigDecimal.ZERO.stripTrailingZeros());
            help.setNumber(0);
            help.setEggLayingNum(BigDecimal.ZERO);
            help.setIsPeople(HamaConfigNumberPeopleEnum.NEW);
            Date hireTime= DateUtils.add(indexTime,hamaConfigNumber.getNumber());
            help.setHireTime(hireTime);
            help.setStartProductionTime(indexTime);
        }else {
            // 查询当前用户蛤蟆卡对应助力速度
            BigDecimal basicSpeed = ObjectUtils.isEmpty(hamaUserMix)? BigDecimal.ZERO: this.hamaConfigNumberService.getBasicSpeed(HamaConfigNumberTypeEnum.TWO, HamaConfigNumberPeopleEnum.OLD, getWaNumber(joinUser.getUserId()));
            help.setBasicSpeed(basicSpeed);
            help.setNumber(ObjectUtils.isEmpty(hamaUserMix)?0:hamaUserMix.getNumber());
            help.setEggLayingNum(BigDecimal.ZERO);
            help.setIsPeople(HamaConfigNumberPeopleEnum.OLD);
            help.setHireTime(null);
            help.setStartProductionTime(indexTime);
        }
        if (!this.hamaHelpService.save(help)) {
            return R.fail("加入队伍失败~");
        }
        return R.ok(teamUser.getNickName(),"加入队伍成功~");
    }

    /**
     * 建设运动场数据
     *
     * @param page 分页对象
     * @return 信息
     */
    public IPage<HamaOpenConfigVO> sportDataConfig(Page<HamaOpenConfig> page) {
        Page<HamaOpenConfig> ipage = this.hamaOpenConfigService.page(page, new LambdaQueryWrapper<HamaOpenConfig>().eq(HamaOpenConfig::getState, 1).orderByDesc(HamaOpenConfig::getSort));
        List<HamaOpenConfigVO> voList = new ArrayList<>();
        if (ObjUtil.isNotEmpty(ipage) && CollUtil.isNotEmpty(ipage.getRecords())) {
            voList = BeanUtil.copyToList(ipage.getRecords(),HamaOpenConfigVO.class);
            voList.forEach(vo->vo.setBasicSpeed(MoneyUtils.toBigDecimal2(vo.getBasicSpeed())));
        }
        IPage<HamaOpenConfigVO> voPage = new Page<>();
        voPage.setRecords(voList);
        voPage.setTotal(ipage.getTotal());
        return voPage;
    }

    /**
     * 我的运动场数据
     *
     * @param page 分页对象
     * @param userId 用户id
     * @return 信息
     */
    public IPage<HamaUserOpenVo> myBuildSport(Page<HamaUserOpen> page, Long userId) {
        Page<HamaUserOpen> ipage = this.hamaUserOpenService.page(page, new LambdaQueryWrapper<HamaUserOpen>().eq(HamaUserOpen::getUserId,userId).eq(HamaUserOpen::getIsHire,1).orderByDesc(HamaUserOpen::getCreateTime));
        List<HamaUserOpenVo> voList = new ArrayList<>();
        if (ObjUtil.isNotEmpty(ipage) && CollUtil.isNotEmpty(ipage.getRecords())) {
            List<HamaOpenConfig> openConfigs = this.hamaOpenConfigService.list();
            Map<Long, HamaOpenConfig> configMap = openConfigs.stream().collect(Collectors.toMap(HamaOpenConfig::getId, Function.identity()));//运动场数据
            voList = BeanUtil.copyToList(ipage.getRecords(),HamaUserOpenVo.class);
            voList.forEach(open -> {
                open.setBasicSpeed(MoneyUtils.multipleToScale2(open.getBasicSpeed(),24));//每天产多少力豆
                open.setHireDay(configMap.get(open.getOpenConfigId()).getHireDays());
                open.setEggLayingNum(MoneyUtils.toBigDecimal2(open.getEggLayingNum()));
            });
        }
        IPage<HamaUserOpenVo> voPage = new Page<>();
        voPage.setRecords(voList);
        voPage.setTotal(ipage.getTotal());
        return voPage;
    }

    /**
     * 建设运动场
     *
     * @param userId 用户id
     * @param openId 运动场id
     * @return 信息
     */
    @Transactional
    public R<String> userBuildSport(Long userId, Long openId) {
        Date indexTime = new Date();
        // 查询开辟灵池id是否存在。
        HamaOpenConfig hamaOpenConfig=this.hamaOpenConfigService.getById(openId);
        if(ObjectUtils.isEmpty(hamaOpenConfig)){
            return R.fail("参数错误~");
        }
        if(hamaOpenConfig.getState()==HamaOpenConfigStateEnum.HIDE){
            return R.fail("参数错误~");
        }

        //检查用户是否存在对应灵池要求、是否上限
        int isOpenNumber=hamaOpenConfig.getIsOpenNumber();
        Long count = this.hamaUserOpenService.lambdaQuery().eq(HamaUserOpen::getUserId, userId).eq(HamaUserOpen::getOpenConfigId, openId).eq(HamaUserOpen::getIsHire, HamaMixLogHireEnum.YES).count();
        if(count+1>isOpenNumber){
            return R.fail("当前运动场建设已达上限数量~");
        }

        // 查询力豆余额，判断力豆
        int beadNumber=hamaOpenConfig.getBeadNumber();
        if (beadNumber > 0) {
            BigDecimal lidou = this.userAssetLidouService.getLidouInfo(userId).getAmount();
            if(lidou.compareTo(new BigDecimal(beadNumber)) < 0){
                return R.fail("力豆不足~");
            }
        }

        // 查询手环藏品余量,判断手环
        int hamaNumber=hamaOpenConfig.getHamaNumber();
        Long[] nftLeaveInfo = null;
        if (hamaNumber > 0) {
            nftLeaveInfo = this.hamaMixConfigService.getNftLeaveInfo(hamaOpenConfig.getNftId(),userId, hamaNumber);
            int num = nftLeaveInfo==null?0: nftLeaveInfo.length;
            if(num<hamaNumber){
                return R.fail(num==0?"还没有运动场~":"运动场数量不足，只有"+num+"张~");
            }
        }

        //建设运动场
        HamaUserOpen hamaUserOpen=new HamaUserOpen();
        hamaUserOpen.setUserId(userId);
        hamaUserOpen.setName(hamaOpenConfig.getName());
        hamaUserOpen.setHamaNumber(hamaOpenConfig.getHamaNumber());
        hamaUserOpen.setToplimit(hamaOpenConfig.getToplimit());
        hamaUserOpen.setBasicSpeed(hamaOpenConfig.getBasicSpeed());
        hamaUserOpen.setEggLayingNum(BigDecimal.ZERO);
        hamaUserOpen.setStartProductionTime(indexTime);
        Date hireTime=DateUtils.add(indexTime,hamaOpenConfig.getHireDays());
        hamaUserOpen.setHireTime(hireTime);
        hamaUserOpen.setIsHire(HamaMixLogHireEnum.YES);
        hamaUserOpen.setWaNumber(hamaOpenConfig.getWaNumber());
        hamaUserOpen.setOpenConfigId(hamaOpenConfig.getId());
        if (!this.hamaUserOpenService.save(hamaUserOpen)) {
            return R.fail("建设运动场失败~");
        }

        //销毁力豆
        if (beadNumber > 0) {
            this.userAssetLidouService.updateLidouBalance(
                    userId,
                    WalletLidouChangeTypeEnum.SPORT_BUILD_CONSUME,
                    WalletChangeDirectionEnum.OUT,
                    new BigDecimal(beadNumber),
                    hamaUserOpen.getId(),
                    WalletLidouChangeTypeEnum.SPORT_BUILD_CONSUME.getMsg());
        }

        //销毁手环
        if (hamaNumber > 0) {
            this.hamaMixConfigService.burnNftLeaveInfo(nftLeaveInfo,userId,UserNftStatusEnum.SPORT_BUILD_BURN);
        }

        //添加创建此运动场的人数
        this.hamaOpenConfigService.addBuildSportNumber(openId,1);

        return R.ok_msg("建设运动场成功~");
    }

    //*****************************************************************************************************************
    //***********************************************app相关封装*********************************************************
    //*****************************************************************************************************************


    /**
     * 多装备投放获取蛙星人数量
     *
     * @param userId 用户id
     * @return num
     */
    public Integer getWaNumber(Long userId){ // 获取所有可投放装备的数据
        int waNumber = 0;
        List<HamaMixLog> list = this.hamaMixLogService.lambdaQuery().eq(HamaMixLog::getUserId, userId).eq(HamaMixLog::getIsHire, HamaMixLogHireEnum.YES).list();
        if (CollUtil.isNotEmpty(list)) {
            Map<Long, List<HamaMixLog>> collect = list.stream().collect(Collectors.groupingBy(HamaMixLog::getNftId));
            List<HamaMixConfig> configs = this.hamaMixConfigService.getCacheData(true);
            Map<Long, Integer> mixConfigMap = configs.stream().collect(Collectors.toMap(HamaMixConfig::getNftId, HamaMixConfig::getSportMix));
            for (Map.Entry<Long, List<HamaMixLog>> entry : collect.entrySet()) {
                Long nftId = entry.getKey();
                List<HamaMixLog> mixLogs = entry.getValue();
                int sum = mixLogs.stream().mapToInt(HamaMixLog::getHamaNumber).sum();//该类装备在空投周期内，已投放的数量
                int wa = sum * mixConfigMap.get(nftId);// 该类装备所达的蛙星人数量
                waNumber += wa;
            }
        }
        return waNumber;
    }

    /**
     * 获取已投放藏品的对应数量
     *
     * @param userId
     * @return
     */
    public Map<Long,Integer> getNftNumber(Long userId){
        Map<Long,Integer> res = null;
        List<HamaMixLog> list = this.hamaMixLogService.lambdaQuery().eq(HamaMixLog::getUserId, userId).eq(HamaMixLog::getIsHire, HamaMixLogHireEnum.YES).list();
        if (CollUtil.isNotEmpty(list)) {
            res = new HashMap<>();
            Map<Long, List<HamaMixLog>> collect = list.stream().collect(Collectors.groupingBy(HamaMixLog::getNftId));
            for (Map.Entry<Long, List<HamaMixLog>> entry : collect.entrySet()) {
                Long nftId = entry.getKey();
                List<HamaMixLog> mixLogs = entry.getValue();
                int sum = mixLogs.stream().mapToInt(HamaMixLog::getHamaNumber).sum();//该类装备在空投周期内，已投放的数量
                res.put(nftId,sum);
            }
        }
        return res;
    }

    /**
     * 判断加入队伍的用户 - 不能加入自己队员创建的队伍
     *
     * @param joinUserId 加入队伍的用户id
     * @param teamUserId 加入队伍的队长id
     */

    private void joinTeamJudge(Long joinUserId,Long teamUserId){
        HamaHelp one = this.hamaHelpService.lambdaQuery().eq(HamaHelp::getChildUserId, teamUserId).last("limit 1").one();
        if (ObjUtil.isNotEmpty(one)) {
            if (Objects.equals(one.getParentUserId(),joinUserId)) {
                throw new ServiceException("不能加入自己队员创建的队伍~");
            }
            joinTeamJudge(joinUserId,one.getParentUserId());
        }
    }

    public void verifyIsOpenSport(){
        Assert.isTrue(isOpen(),()->new ServiceException("运动场周末关闭~"));
    }

    public boolean isOpen(){
        Integer isOpen = this.sysConfigService.getValue(Config.Sys.Sport.运动场开关);
        if (isOpen == null) return false;
        return isOpen == 1;
    }

    /**
     * 验证是否正在空投中，在提醒用户等会操作
     *
     */
    public void verifyInAirdrop(){
        Integer state = redisCache.getCacheObject(RedisKey.SPORT_IN_AIRDROP);
        Assert.isFalse(state!=null && state==1,()->new ServiceException("正在结算空投结果，请1分钟后投放~"));
    }


    /**
     * 添加收益
     *
     * @param userId 用户id
     * @param sourceId 源id
     * @param income 收益
     * @param typeEnum 收益类型
     */
    public void addIncome(Long userId,Long sourceId, BigDecimal income, WalletLidouChangeTypeEnum typeEnum){
        Assert.notNull(userId,()->new ServiceException("用户id不能为空~"));
        Assert.notNull(income,()->new ServiceException("用户收入不能为空~"));
        Assert.notNull(typeEnum,()->new ServiceException("收入类型不能为空~"));
        Assert.isTrue(typeEnum==WalletLidouChangeTypeEnum.SPORT_MIX_INCOME
                || typeEnum==WalletLidouChangeTypeEnum.SPORT_TEAM_INCOME_NEW
                || typeEnum==WalletLidouChangeTypeEnum.SPORT_TEAM_INCOME_OLD
                || typeEnum==WalletLidouChangeTypeEnum.SPORT_BUILD_INCOME
                || typeEnum==WalletLidouChangeTypeEnum.SPORT_TEAM_INCOME_NEW_NEXT
                || typeEnum==WalletLidouChangeTypeEnum.SPORT_TEAM_INCOME_OLD_NEXT,()->new ServiceException("收入类型不支持~"));
        // 只有开启了运动场，才空投
        if (isOpen()) {
            this.userAssetLidouService.updateLidouBalance(userId,typeEnum, WalletChangeDirectionEnum.IN,income,sourceId,typeEnum.getMsg());
        }
    }

    //*****************************************************************************************************************
    //***********************************************运动场空投相关*******************************************************
    //*****************************************************************************************************************

    /**
     * 运动场装备加油手环空投力豆
     *
     */
    public void airdropSportMix(){
        List<HamaUserMix> userMixList = this.list(new QueryWrapper<HamaUserMix>().select("DISTINCT user_id").gt("basic_speed",0));
        if(CollectionUtils.isEmpty(userMixList)){
            log.info("空投任务mix：运动场还没有用户投放装备 或 有效空投天数的装备~");
            return;
        }
        List<List<HamaUserMix>> split = ListUtil.split(userMixList, 20);
        for(int i=0;i<split.size();i++) {
            List<HamaUserMix> newList=split.get(i);
            List<Long> userIds=newList.stream().map(HamaUserMix::getUserId).collect(Collectors.toList());
            // 添加到仓库-走MQ异步处理
            mqSender.sendDelay(AppMqDelayEnum.SPORT_MIX, userIds,0L);
        }
    }

    /**
     * 运动场队员助力空投力豆
     *
     */
    public void airdropSportTeam(){
        List<HamaHelp> hamaHelpList = this.hamaHelpService.lambdaQuery().select(HamaHelp::getParentUserId).eq(HamaHelp::getIsPeople,HamaConfigNumberPeopleEnum.ADMIN).list();
        if(CollectionUtils.isEmpty(hamaHelpList)){
            log.info("空投任务team：运动场还没有用户创建队伍~");
            return;
        }
        List<Long> userIds=hamaHelpList.stream().map(HamaHelp::getParentUserId).collect(Collectors.toList());
        // 添加到仓库-走MQ异步处理
        mqSender.sendDelay(AppMqDelayEnum.SPORT_TEAM, userIds,0L);
/*        List<List<HamaHelp>> split = ListUtil.split(hamaHelpList, 20);
        for(int i=0;i<split.size();i++) {
            List<HamaHelp> newList=split.get(i);
            List<Long> userIds=newList.stream().map(HamaHelp::getParentUserId).collect(Collectors.toList());
            // 添加到仓库-走MQ异步处理
            mqSender.sendDelay(AppMqDelayEnum.SPORT_TEAM, userIds,0L);
        }*/
    }

    /**
     * 构建运动场空投力豆
     *
     */
    public void airdropSportBuild() {
        List<HamaUserOpen> userOpenList = this.hamaUserOpenService.lambdaQuery().eq(HamaUserOpen::getIsHire, HamaMixLogHireEnum.YES).list();
        if (CollectionUtils.isEmpty(userOpenList)) {
            log.info("空投任务mix：运动场还没有用户建设运动场 或 有效雇佣天数的运动场~");
            return;
        }
        List<Long> openIds=userOpenList.stream().map(HamaUserOpen::getId).collect(Collectors.toList());
        // 添加到仓库-走MQ异步处理
        mqSender.sendDelay(AppMqDelayEnum.SPORT_BUILD, openIds,0L);
/*        List<List<HamaUserOpen>> split = ListUtil.split(userOpenList, 20);
        for(int i=0;i<split.size();i++) {
            List<HamaUserOpen> newList=split.get(i);
            List<Long> openIds=newList.stream().map(HamaUserOpen::getId).collect(Collectors.toList());
            // 添加到仓库-走MQ异步处理
            mqSender.sendDelay(AppMqDelayEnum.SPORT_BUILD, openIds,0L);
        }*/
    }

    //*****************************************************************************************************************
    //***********************************************后台相关************************************************************
    //*****************************************************************************************************************

    /**
     * 运动场投装备配置列表
     *
     * @param dto 传输对象
     * @return 分页列表
     */
    public IPage<WebHamaMixConfigVo> webMixConfig(WebHamaMixConfigDto<WebHamaMixConfigVo> dto) {
        return this.hamaMixConfigService.getBaseMapper().webMixConfig(dto.newPage(),dto.getState(),dto.getNftName());
    }


    /**
     * 运动场投装备配置-禁用/启用
     *
     * @param configId 运动场投装备的配置id
     * @param state 1-启用/2-禁用
     */
    @Transactional
    public void mixEnable(Long configId, Integer state) {
        boolean update = this.hamaMixConfigService.lambdaUpdate().set(HamaMixConfig::getState, state).eq(HamaMixConfig::getId, configId).update();
        Assert.isTrue(update,"运动场投装备配置-禁用/启用失败~");
        redisCache.deleteObject(RedisKey.SPORT_MIX_CONFIG);
    }


    public WebHamaMixConfigVo mixInfo(Long configId) {
        Assert.notNull(this.hamaMixConfigService.getById(configId),"未查询到配置信息~");
        return this.hamaMixConfigService.getBaseMapper().webMixConfigInfo(configId);
    }

    @Transactional
    public void mixUpdate(WebHamaMixConfigDto2 vo2) {
        this.hamaMixConfigService.lambdaQuery().eq(HamaMixConfig::getNftId,vo2.getNftId()).ne(vo2.getId()!=null,HamaMixConfig::getId,vo2.getId()).oneOpt().ifPresent(l->{
            throw new ServiceException("当前藏品已配置~");
        });
        HamaMixConfig config = BeanUtil.copyProperties(vo2,HamaMixConfig.class);
        boolean b = this.hamaMixConfigService.saveOrUpdate(config);
        Assert.isTrue(b,String.format("运动场投装备配置%s失败~",vo2.getId()==null?"新增":"编辑"));
        redisCache.deleteObject(RedisKey.SPORT_MIX_CONFIG);
    }


    /**
     * 获取对应配置类型的基础速率
     *
     * @param typeEnum 配置类型
     * @return 基础速率列表
     */
    public List<HamaConfigNumberVo> basicSpeedData(HamaConfigNumberConfigTypeEnum typeEnum) {
        List<HamaConfigNumber> list = this.hamaConfigNumberService.lambdaQuery().eq(HamaConfigNumber::getConfigType, typeEnum).orderByAsc(HamaConfigNumber::getNumber).list();
        return CollUtil.isEmpty(list)?new ArrayList<>(0):BeanUtil.copyToList(list,HamaConfigNumberVo.class);
    }

    /**
     * 获取助力的基础速率
     *
     * @return 基础速率列表
     */
    public HamaConfigNumberTeamVo basicSpeedDataTeam() {
        // 新人助力数据
        List<HamaConfigNumberVo> newPeople = basicSpeedData(HamaConfigNumberConfigTypeEnum.THREE);
        HamaConfigNumberVo vo = CollUtil.isNotEmpty(newPeople)?newPeople.get(0):null;
        boolean notEmpty = ObjUtil.isNotEmpty(vo);
        // 老人助力数据
        List<HamaConfigNumberVo> oldPeople = basicSpeedData(HamaConfigNumberConfigTypeEnum.TWO);
        // 几天内注册实名为新人
        Integer day = this.sysConfigService.getValue(Config.Sys.Sport.几天内注册的用户加入运动场算新人);
        // 返回
        return HamaConfigNumberTeamVo.builder()
                .id(notEmpty?vo.getId():null)
                .number(notEmpty? vo.getNumber() : null)
                .basicSpeed(notEmpty? vo.getBasicSpeed() : BigDecimal.ZERO)
                .configType(notEmpty? vo.getConfigType() : null)
                .day(day)
                .factor(this.sysConfigService.getValue(Config.Sys.Sport.间推助力系数))
                .oldConfigNumber(oldPeople)
                .build();
    }

    /**
     * 新增编辑基础速率
     *
     * @param dto 传输对象
     */
    @Transactional
    public void basicSpeedUpdate(List<HamaConfigNumberDto> dto) {
        Map<HamaConfigNumberConfigTypeEnum, List<HamaConfigNumberDto>> collect = dto.stream().collect(Collectors.groupingBy(HamaConfigNumberDto::getConfigType));
        Assert.isFalse(collect.size()>1,"配置类型错误~");
        for (Map.Entry<HamaConfigNumberConfigTypeEnum, List<HamaConfigNumberDto>> entry : collect.entrySet()) {
            HamaConfigNumberConfigTypeEnum key = entry.getKey();
            List<HamaConfigNumberDto> value = entry.getValue();
            List<HamaConfigNumber> configNumbers = BeanUtil.copyToList(value,HamaConfigNumber.class);
            int size = 0;
            if ((size=configNumbers.size())>1) {
                Set<Integer> numberSet = configNumbers.stream().map(HamaConfigNumber::getNumber).collect(Collectors.toSet());
                Assert.isFalse(numberSet.size() < size,"蛙星人数量配置重复~");
                Set<BigDecimal> basicSpeedSet = configNumbers.stream().map(HamaConfigNumber::getBasicSpeed).collect(Collectors.toSet());
                Assert.isFalse(basicSpeedSet.size() < size,"蛙星人速率配置重复~");
                // configNumbers 按照 number 升序，然后判断 basicSpeed 是否下一个比上一个大，如果不是抛出异常
                configNumbers.sort(Comparator.comparing(HamaConfigNumber::getNumber));
                for (int i = 1; i < configNumbers.size(); i++) {
                    BigDecimal currentBasicSpeed = configNumbers.get(i).getBasicSpeed();
                    BigDecimal previousBasicSpeed = configNumbers.get(i - 1).getBasicSpeed();
                    if (currentBasicSpeed.compareTo(previousBasicSpeed) <= 0) {
                        throw new IllegalArgumentException("蛙星人速率配置错误~");
                    }
                }
            }
            if (key == HamaConfigNumberConfigTypeEnum.ONE) {
                configNumbers.forEach(c->{c.setType(HamaConfigNumberTypeEnum.ONE);c.setIsPeople(HamaConfigNumberPeopleEnum.OLD);});
            }
            if (key == HamaConfigNumberConfigTypeEnum.TWO) {
                configNumbers.forEach(c->{c.setType(HamaConfigNumberTypeEnum.TWO);c.setIsPeople(HamaConfigNumberPeopleEnum.OLD);});
            }
            if (key == HamaConfigNumberConfigTypeEnum.THREE) {
                Assert.isFalse(size==0,"新人助力配置错误~");
                configNumbers.forEach(c->{c.setType(HamaConfigNumberTypeEnum.TWO);c.setIsPeople(HamaConfigNumberPeopleEnum.NEW);});
            }
            this.hamaConfigNumberService.saveOrUpdateBatch(configNumbers);
        }
    }

    /**
     * 新增编辑基础速率(助力)
     *
     * @param dto 传输对象
     */
    @Transactional
    public void basicSpeedTeamUpdate(HamaConfigNumberTeamDto dto) {
        // 更新新人助力速率
        basicSpeedUpdate(Arrays.asList(HamaConfigNumberDto.builder().id(dto.getId()).number(dto.getNumber()).basicSpeed(dto.getBasicSpeed()).configType(dto.getConfigType()).build()));
        // 更新老人助力速率
        basicSpeedUpdate(dto.getOldConfigNumber());
        // 更新几天内注册实名为新人
        sysConfigService.updateConfig(Config.Sys.Sport.几天内注册的用户加入运动场算新人, dto.getDay());
        // 更新间推助力系数
        sysConfigService.updateConfig(Config.Sys.Sport.间推助力系数, dto.getFactor());
        // 更新缓存
        sysConfigService.resetConfigCache();
    }


    /**
     * 移除基础速率配置
     *
     * @param id 配置id
     */
    public void basicSpeedDelete(Long id) {
        Assert.notNull(this.hamaConfigNumberService.getById(id),"为查询到要移除的配置信息~");
        Assert.isTrue(this.hamaConfigNumberService.removeById(id),"移除失败~");
    }

    /**
     * 队伍队长列表
     *
     * @param dto 传输列表
     * @return 列表
     */
    public IPage<HamaHelpAdminVO> selectTeamAdmins(HamaHelpAdminDto<HamaHelpAdminVO> dto) {
        return this.hamaHelpService.selectTeamAdmins(dto.newPage(), dto.getSearch());
    }


    /**
     * 队伍成员详情
     *
     * @param dto 传输列表
     * @return 列表
     */
    public IPage<HamaHelpMemberVO> selectTeamMembers(HamaHelpMemberDto<HamaHelp> dto) {
        IPage<HamaHelp> page = this.hamaHelpService.getBaseMapper().selectTeamMembers(dto.newPage(),dto.getUserId());
        IPage<HamaHelpMemberVO> iPage = new Page<>();
        if (ObjUtil.isNotEmpty(page) && CollUtil.isNotEmpty(page.getRecords())) {
            BigDecimal factor = this.sysConfigService.getValue(Config.Sys.Sport.间推助力系数);
            iPage.setTotal(page.getTotal());
            List<HamaHelpMemberVO> memberVOS = new ArrayList<>();
            for (HamaHelp record : page.getRecords()) {
                List<HamaHelpNftVO> vos = this.hamaHelpService.getBaseMapper().selectHelpNftvos(record.getChildUserId());
                int member = 2;
                if (record.getIsRealName()) {
                    member = 1;
                }
                if (record.getBasicSpeed().compareTo(BigDecimal.ZERO)>0) {
                    member = 1;
                }
                HamaHelpMemberVO build = HamaHelpMemberVO.builder()
                        .memberUserId(record.getChildUserId())
                        .people(record.getIsPeople().getValue())
                        .member(member)
                        .type(record.getType())
                        .waMember(getWaNumber(record.getChildUserId()))
                        .airdropSpeed(record.getType()==1?record.getBasicSpeed():record.getBasicSpeed().multiply(factor).setScale(6, RoundingMode.HALF_UP).stripTrailingZeros())
                        .airdropTotal(DateUtil.between(Date.from(record.getCreateTime().atZone(ZoneId.systemDefault()).toInstant()), new Date(), DateUnit.HOUR))
                        .helpNfts(vos)
                        .build();
                memberVOS.add(build);
            }
            iPage.setRecords(memberVOS);
        }
        return iPage;
    }

    /**
     * 运动场建设配置列表
     *
     * @param dto 传输列表
     * @return 列表
     */
    public IPage<WebHamaOpenConfigVo> selectBuildList(HamaBuildDto<HamaHelpAdminVO> dto) {

        return this.hamaOpenConfigService.getBaseMapper().selectBuildList(dto.newPage(),dto.getSearch());
    }














































    /**
     * 运动场建设配置信息
     *
     * @param id 传输列表
     * @return 列表
     */
    public WebHamaOpenConfigVo selectBuildInfo(Long id) {
        Assert.notNull(this.hamaOpenConfigService.getById(id),"未查询到当前建设运动场配置信息~");
        return this.hamaOpenConfigService.getBaseMapper().selectBuildInfo(id);
    }

    /**
     * 运动场建设-禁用/启用
     *
     * @param configId 运动场建设的配置id
     * @param state 1-启用/2-禁用
     */
    @Transactional
    public void buildEnable(Long configId, Integer state) {
        Assert.notNull(this.hamaOpenConfigService.getById(configId),"未查询到配置信息~");
        boolean update = this.hamaOpenConfigService.lambdaUpdate().set(HamaOpenConfig::getState, state).eq(HamaOpenConfig::getId, configId).update();
        Assert.isTrue(update,"运动场建设配置-禁用/启用失败~");
    }

    /**
     *
     *运动场建设-新增/编辑
     *
     * @param dto 传输对象
     */
    @Transactional
    public void buildUpdate(WebHamaOpenConfigDto dto) {
        HamaOpenConfig config = BeanUtil.copyProperties(dto,HamaOpenConfig.class);
        boolean b = this.hamaOpenConfigService.saveOrUpdate(config);
        Assert.isTrue(b,"运动场建设配置-新增/修改失败~");
    }
}